﻿using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MediatR;

namespace MangoMes.Write.API.Applications.ArrivalNotice
{
    public class NoticelinesSeachHandler : IRequestHandler<NoticelinesSeachCommand, PageDTO<NoticelinesDto>>
    {
        #region 仓储
        /// <summary>
        /// 仓储
        /// </summary>
        private readonly IBateRepository<NoticelinesDto> NoticelinesDtoRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="NoticelinesDtoRepository"></param>
        public NoticelinesSeachHandler(IBateRepository<NoticelinesDto> NoticelinesDtoRepository)
        {
            this.NoticelinesDtoRepository = NoticelinesDtoRepository;
        }
        #endregion

        #region 到货通知单单行 列表
        /// <summary>
        /// 到货通知单单行 列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PageDTO<NoticelinesDto>> Handle(NoticelinesSeachCommand request, CancellationToken cancellationToken)
        {
            //异常处理
            try
            {
                //初始化一个ResultDTO<ProdlineDto>对象result，并设置Code为 0
                PageDTO<NoticelinesDto> result = new PageDTO<NoticelinesDto>();

                var pageNum = (request.pageIndex - 1) * request.pageSize;
                DapperHelper dapperHelper = new DapperHelper();
                NoticelinesDto dto = new NoticelinesDto();

                //连接mySql 
                string conn = dapperHelper.MangoMesWrite;

                //sql语句
                string str = $"select * from noticelines a join productmanage b on a.productManageNode = b.productManageNode WHERE a.ArrivalNoticeNode='{request.ArrivalNoticeNode}'";

                var list = NoticelinesDtoRepository.GetAll(str, dto, conn).ToList();

                result.TotalCount = list.Count(); //计算list列表中元素个数
                result.PageCount = (int)Math.Ceiling((list.Count() * 1.0) / request.pageSize); //表示总的记录数量
                list = list.OrderBy(x => x.NoticeLineId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
                result.Data = list; //计算总页数

                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion

    }
}
